package com.seguriapp.configuration;

import java.io.InputStream;
import java.lang.reflect.Method;

import org.apache.log4j.Logger;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class InitServiceImpl {

  private static final String CONFIG_FILE_NAME = "configFile.xml";
  private static final String POSTAL_CODE_LIST_FILE_NAME = "postalCodeList.xml";
  private static final String MAP_RELATIONS_LIST_FILE_NAME = "mapRelations.xml";
  private static final String METHOD_INSTANCE = "getInstance";
  private static final Logger LOGGER = Logger.getLogger(InitServiceImpl.class);

  public InitServiceImpl() {
    Serializer serializer = new Persister();
    try {
      final Method globalConfigLoaderMethod = Class.forName(GlobalConfigLoader.class.getName()).getMethod(METHOD_INSTANCE, new Class[0]);
      GlobalConfigLoader globalConfigLoader = (GlobalConfigLoader) globalConfigLoaderMethod.invoke(null, new Object[0]);
      globalConfigLoader.init(serializer.read(GlobalConfig.class, toInputStream(CONFIG_FILE_NAME)));

      final Method postalCodeListLoaderMethod = Class.forName(PostalCodeListLoader.class.getName()).getMethod(METHOD_INSTANCE, new Class[0]);
      PostalCodeListLoader postalCodeListLoader = (PostalCodeListLoader) postalCodeListLoaderMethod.invoke(null, new Object[0]);
      postalCodeListLoader.init(serializer.read(PostalCodeList.class, toInputStream(POSTAL_CODE_LIST_FILE_NAME)));

      final Method mapRelationsListLoaderMethod = Class.forName(MapRelationsListLoader.class.getName()).getMethod(METHOD_INSTANCE, new Class[0]);
      MapRelationsListLoader mapRelationsListLoader = (MapRelationsListLoader) mapRelationsListLoaderMethod.invoke(null, new Object[0]);
      mapRelationsListLoader.init(serializer.read(MapRelationsList.class, toInputStream(MAP_RELATIONS_LIST_FILE_NAME)));
    } catch (Exception e) {
      LOGGER.error("Error loading configuration files \n", e);
    }
  }

  /**
   * Converts a String into a InputStream
   */
  private InputStream toInputStream(final String name) {
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    return loader.getResourceAsStream(name);
  }
}
